﻿using System;
using System.IO;
using System.Windows.Forms;
using FBroSharp;            // ⚠️ #1 MOST CRITICAL! FBroSharpControl, FBroSharpBrowserListControl
using FBroSharp.Lib;        // ⚠️ CRITICAL! IFBroSharpBrowser, IFBroSharpFrame
using FBroSharp.Value;      // ⚠️ CRITICAL! FBroSharpWindowsInfo, FBroSharpBrowserSetting
using FBroSharp.Event;      // ⚠️ REQUIRED! FBroSharpBrowserEvent
using FBroSharp.DataType;   // ⚠️ REQUIRED! FBroSharpEventDisableControl
using FBroSharp.Const;      // ⚠️ REQUIRED! Constants

namespace JavaScript对话框自动化处理器
{
    public partial class Form1 : Form
    {
        private IFBroSharpBrowser browser;
        private JSDialogHandler dialogHandler;
        private const string BROWSER_USER_FLAG = "js_dialog_browser";
        private int dialogCount = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 创建对话框处理器
                dialogHandler = new JSDialogHandler(this);
                
                // 设置默认URL为本地alert.html
                string alertHtmlPath = Path.Combine(Directory.GetCurrentDirectory(), "alert.html");
                if (File.Exists(alertHtmlPath))
                {
                    txtUrl.Text = "file:///" + alertHtmlPath.Replace("\\", "/");
                }
                
                // 创建浏览器
                CreateBrowser();
                
                AddLog("JavaScript对话框处理器已启动");
                AddLog($"默认响应方式: {cmbAutoResponse.SelectedItem}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 创建浏览器
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 创建窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowsInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // ⚠️ CRITICAL for embedded browser!
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "JS Dialog Browser"
                };

                // 创建浏览器设置
                FBroSharpBrowserSetting browserSetting = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(dialogHandler);

                // 创建浏览器
                bool success = FBroSharpControl.CreatBrowser(
                    txtUrl.Text,
                    windowsInfo,
                    browserSetting,
                    null,  // request_context
                    null,  // extra_info
                    browserEvent,
                    default,  // ✅ Use default for struct value type!
                    BROWSER_USER_FLAG
                );

                if (!success)
                {
                    throw new Exception("浏览器创建失败");
                }

                // 异步获取浏览器实例
                System.Threading.Thread.Sleep(500);
                browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);

                if (browser != null && browser.IsValid)  // ⚠️ IsValid is PROPERTY, not method!
                {
                    AddLog("浏览器创建成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 导航按钮点击
        /// </summary>
        private void btnNavigate_Click(object sender, EventArgs e)
        {
            try
            {
                if (browser != null && browser.IsValid)
                {
                    var mainFrame = browser.GetMainFrame();
                    if (mainFrame != null)
                    {
                        mainFrame.LoadURL(txtUrl.Text);
                        AddLog($"导航到: {txtUrl.Text}");
                    }
                }
                else
                {
                    MessageBox.Show("浏览器未就绪", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 测试Alert对话框
        /// </summary>
        private void btnTestAlert_Click(object sender, EventArgs e)
        {
            try
            {
                if (browser != null && browser.IsValid)
                {
                    var mainFrame = browser.GetMainFrame();
                    if (mainFrame != null)
                    {
                        mainFrame.ExecuteJavaScript("alert('这是一个测试警告框');", "", 0);
                        AddLog("触发Alert对话框测试");
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试Confirm对话框
        /// </summary>
        private void btnTestConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (browser != null && browser.IsValid)
                {
                    var mainFrame = browser.GetMainFrame();
                    if (mainFrame != null)
                    {
                        mainFrame.ExecuteJavaScript("var result = confirm('确认执行此操作吗？'); console.log('Confirm结果:', result);", "", 0);
                        AddLog("触发Confirm对话框测试");
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试Prompt对话框
        /// </summary>
        private void btnTestPrompt_Click(object sender, EventArgs e)
        {
            try
            {
                if (browser != null && browser.IsValid)
                {
                    var mainFrame = browser.GetMainFrame();
                    if (mainFrame != null)
                    {
                        mainFrame.ExecuteJavaScript("var input = prompt('请输入您的姓名:', '默认值'); console.log('Prompt输入:', input);", "", 0);
                        AddLog("触发Prompt对话框测试");
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加日志（UI线程安全）
        /// </summary>
        public void AddLog(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(AddLog), message);
                return;
            }

            string logEntry = $"[{DateTime.Now:HH:mm:ss}] {message}";
            lstDialogLog.Items.Add(logEntry);
            if (lstDialogLog.Items.Count > 0)
            {
                lstDialogLog.TopIndex = lstDialogLog.Items.Count - 1;
            }

            if (chkEnableLogging.Checked)
            {
                Console.WriteLine(logEntry);
            }
        }

        /// <summary>
        /// 更新对话框统计
        /// </summary>
        public void UpdateDialogStatistics(int count)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<int>(UpdateDialogStatistics), count);
                return;
            }

            dialogCount = count;
            lblDialogCount.Text = $"已处理对话框: {dialogCount}";
        }

        /// <summary>
        /// 获取自动响应方式
        /// </summary>
        public string GetAutoResponse()
        {
            if (InvokeRequired)
            {
                return (string)Invoke(new Func<string>(GetAutoResponse));
            }
            return cmbAutoResponse.SelectedItem?.ToString() ?? "accept";
        }

        /// <summary>
        /// 获取Prompt输入内容
        /// </summary>
        public string GetPromptInput()
        {
            if (InvokeRequired)
            {
                return (string)Invoke(new Func<string>(GetPromptInput));
            }
            return txtPromptInput.Text;
        }

        /// <summary>
        /// 是否启用日志
        /// </summary>
        public bool IsLoggingEnabled()
        {
            if (InvokeRequired)
            {
                return (bool)Invoke(new Func<bool>(IsLoggingEnabled));
            }
            return chkEnableLogging.Checked;
        }

        /// <summary>
        /// 窗体大小改变时调整浏览器大小
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// Panel大小改变时调整浏览器大小
        /// </summary>
        private void panelBrowser_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                if (browser != null && browser.IsValid)
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Resize browser failed: {ex.Message}");
            }
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (browser != null && browser.IsValid)
                {
                    browser.CloseBrowser(false, false);
                    AddLog("浏览器已关闭");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        private void btnClearLog_Click(object sender, EventArgs e)
        {
            lstDialogLog.Items.Clear();
            AddLog("日志已清空");
        }
    }
}
